package com.syj.collect.model;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.syj.collect.Present.UserPresent;
import com.syj.collect.app.R;
import com.syj.collect.base.BaseMvpAvtivity;
import com.syj.collect.entry.TagAdapterData;
import com.syj.collect.entry.TaskBean;
import com.syj.collect.entry.UpdataHead;
import com.syj.collect.entry.UpdataPass;
import com.syj.collect.entry.UserInfoBean;
import com.syj.collect.http.ApiServise;
import com.syj.collect.http.BaseObserver;
import com.syj.collect.http.BaseRequest;
import com.syj.collect.utils.Glide4Engine;
import com.syj.collect.utils.GlideUtils;
import com.syj.collect.utils.GsonUtil;
import com.syj.collect.utils.HttpUtils;
import com.syj.collect.utils.LogUtils;
import com.syj.collect.utils.SPUtil;
import com.syj.collect.utils.ToastMgr;
import com.syj.collect.view.UserActivityView;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.apache.commons.lang3.StringEscapeUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.hutool.http.HttpUtil;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MyUserActivity extends BaseMvpAvtivity<UserActivityView, UserPresent> implements UserActivityView {

    @Override
    public UserPresent initPresenter() {
        return new UserPresent();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        initTitle("设置");
        rxPermissions = new RxPermissions(this);
        loadingDialog.create();
        initView();
    }

    private UserInfoBean.UserInfo peopleBean;
    private RelativeLayout relativeLayout;
    private ImageView ivhead;
    private TextView tvname, tvnum;
    private EditText etpassword;//jiumima
    private EditText etpassword1;//xin mi ma
    private EditText etpassword2;// zai  ci que ren mi  ma
    private Button btupdatapass;
    private RxPermissions rxPermissions;

    private void initView() {
        relativeLayout = findViewById(R.id.rl_head);
        ivhead = findViewById(R.id.iv_head);
        etpassword = findViewById(R.id.et_password);
        etpassword1 = findViewById(R.id.et_password1);
        tvname = findViewById(R.id.tv_name);
        tvnum = findViewById(R.id.tv_number);
        etpassword2 = findViewById(R.id.et_password2);
        findViewById(R.id.mexit).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showMissingPermissionDialog();
            }
        });
        btupdatapass = findViewById(R.id.bt_updata_pass);
        String value = SPUtil.getPrefString("userInfo", "");
        Gson gson = new Gson();
        peopleBean = gson.fromJson(value, UserInfoBean.UserInfo.class);
        tvname.setText(peopleBean.getName());
        tvnum.setText(peopleBean.getMobile());
//        Glide.with(this).load(HttpUtils.ImgURL+gBean.getIconUrl()).into(ivhead);

        GlideUtils.Image(ivhead, ApiServise.BASEURLFILE + peopleBean.getIconUrl());
        SpannableString ss = new SpannableString("请输入旧密码");//定义hint的值
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(15, true);//设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        etpassword.setHint(new SpannedString(ss));

        SpannableString s1 = new SpannableString("请输入新密码");//定义hint的值
        AbsoluteSizeSpan as1 = new AbsoluteSizeSpan(15, true);//设置字体大小 true表示单位是sp
        s1.setSpan(as1, 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        etpassword1.setHint(new SpannedString(s1));

        SpannableString s2 = new SpannableString("请确认新密码");//定义hint的值
        AbsoluteSizeSpan as2 = new AbsoluteSizeSpan(15, true);//设置字体大小 true表示单位是sp
        s2.setSpan(as2, 0, s2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        etpassword2.setHint(new SpannedString(s2));


        btupdatapass.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //确认修改密码
                if (etpassword.getText().toString().trim().isEmpty()) {
                    ToastMgr.builder.display("请输入旧密码");
                    return;
                }

                if (etpassword1.getText().toString().trim().isEmpty()) {
                    ToastMgr.builder.display("请输入新密码");
                    return;
                }

                if (etpassword2.getText().toString().trim().isEmpty()) {
                    ToastMgr.builder.display("请再次输入您的密码");
                    return;
                }
                if (!etpassword2.getText().toString().trim().equals(etpassword1.getText().toString().trim())) {
                    ToastMgr.builder.display("新密码不一致,请重新输入");
                    return;
                }
                loadingDialog.show();
                presenter.setNewPassword(etpassword1.getText().toString().trim(), etpassword.getText().toString().trim());
            }
        });

        relativeLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rxPermissions.requestEachCombined(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Permission>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Permission permission) {
                                if (permission.granted) {
                                    //成功获取权限
                                    Matisse.from(MyUserActivity.this)
                                            .choose(MimeType.ofImage())
                                            .capture(true)
                                            .countable(true)
                                            .captureStrategy(new CaptureStrategy(true, "com.syj.collect.app"))
                                            .maxSelectable(3)
                                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                            .thumbnailScale(0.85f)
                                            .imageEngine(new Glide4Engine())//Glide4
                                            .forResult(1);

                                } else if (permission.shouldShowRequestPermissionRationale) {
                                    //用户拒绝权限
                                    ToastMgr.builder.display("您禁止了拍照权限");
                                } else {
                                    //用户禁止权限勾选了不在提示
                                    Intent localIntent = new Intent();
                                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                    localIntent.setData(Uri.fromParts("package", MyUserActivity.this.getPackageName(), null));
                                    startActivity(localIntent);
//                                    LogUtils.i("用户禁止权限勾选了不在提示");
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        });

    }

    List list;
    byte[] bytes;
    List streamlist;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {
            List mSelected = Matisse.obtainResult(data);
            loadingDialog.show();
            // String realPathFromUri = getRealPathFromUri(this, Uri.parse(mSelected.get(0).toString()));
            presenter.upLoadFile(getRealFilePath(this, Uri.parse(mSelected.get(0).toString())));
        }
    }

    /**
     * 根据Uri获取文件真实地址
     */
    public static String getRealFilePath(Context context, Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String realPath = null;
        if (scheme == null)
            realPath = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            realPath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        realPath = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        if (TextUtils.isEmpty(realPath)) {
            if (uri != null) {
                String uriString = uri.toString();
                int index = uriString.lastIndexOf("/");
                String imageName = uriString.substring(index);
                File storageDir;

                storageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);
                File file = new File(storageDir, imageName);
                if (file.exists()) {
                    realPath = file.getAbsolutePath();
                } else {
                    storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    File file1 = new File(storageDir, imageName);
                    realPath = file1.getAbsolutePath();
                }
            }
        }
        return realPath;
    }


    @Override
    public void initSuccess(String str) {

        UpdataHead updataHead = GsonUtil.gsonToBean(str, UpdataHead.class);
        Toast.makeText(this, updataHead.getData().getMsg(), Toast.LENGTH_LONG).show();

        GlideUtils.Image(ivhead, ApiServise.BASEURLFILE + updataHead.getData().getFilePath());
        loadingDialog.dismiss();
        peopleBean.setIconUrl(updataHead.getData().getFilePath());
        SPUtil.setPrefString("userInfo", GsonUtil.gsonString(peopleBean));


    }

    @Override
    public void initFail(String str) {
        Toast.makeText(this, "图片上传失败", Toast.LENGTH_LONG).show();
        loadingDialog.dismiss();
    }

    @Override
    public void updataPas(String val) {
        loadingDialog.dismiss();
        UpdataPass updataPass = GsonUtil.gsonToBean(val, UpdataPass.class);
        if (updataPass.getCode() == 0) {
            ToastMgr.builder.display("密码修改成功");
            finish();
        } else {
            ToastMgr.builder.display(updataPass.getMsg());
        }

    }


    private void showMissingPermissionDialog() {
        try {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("是否退出登录");
           // builder.setMessage("当前应用缺少必要权限。\\n\\n请点击\\\"设置\\\"-\\\"权限\\\"-打开所需权限");

            // 拒绝, 退出应用
            builder.setNegativeButton("取消",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                finish();
                            } catch (Throwable e) {
                                e.printStackTrace();
                            }
                        }
                    });

            builder.setPositiveButton("确认",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SPUtil.clearPreference(MyUserActivity.this);
                            System.exit(0);
                        }
                    });

            builder.setCancelable(false);

            builder.show();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}
